package com.gong.yuanma.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author GongChang
 * @version 1.0
 * @date 2021/6/14 0014 16:14
 */
class Resources {
    private volatile boolean flag = true;//默认开启生产和消费
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    private BlockingQueue<String> blockingQueue = null;

    public Resources(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    //生产者
    public void myProduct() throws InterruptedException {
        String data = null;
        boolean res;
        while (flag){
            data = atomicInteger.incrementAndGet()+"";
            res = blockingQueue.offer(data,2, TimeUnit.SECONDS);
            if (res){
                System.out.println(Thread.currentThread().getName()+"\t 插入队列成功"+data);
            }else {
                System.out.println(Thread.currentThread().getName()+"\t 插入队列失败"+data);
            }
            TimeUnit.SECONDS.sleep(1);
        }

        System.out.println("大老板叫停了");
    }

    //消费者
    public void myConsumer() throws InterruptedException {
        String poll = null;
        while (flag){
            poll = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (poll == null || "".equalsIgnoreCase(poll)){
                System.out.println("获取失败");
                continue;
            }
            System.out.println(Thread.currentThread().getName()+"\t 成功消费了"+poll);
        }
    }

    public void stop(){
        this.flag = false;
    }
}

public class BlockingQueueProducerConsumerDemo {

    public static void main(String[] args) throws InterruptedException {
        Resources resources = new Resources(new ArrayBlockingQueue(3));
        new Thread(()->{
            System.out.println("生产开始");
            try {
                resources.myProduct();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"aa").start();

        new Thread(()->{
            System.out.println("消费开始");
            try {
                resources.myConsumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"bb").start();

        TimeUnit.SECONDS.sleep(7);

        resources.stop();
    }
}
